var cfg = require('../../utils/cfg');
// var socketUtil = require('../../utils/socketUtil');

var app = getApp();


Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    userAva : '',
    userText : '',
    count : 0,
    timeWaitFun : {},
    roomTicket : '',
    roomMaster : '',
    joinPlay : false,
    modelType : 0,
    showStart: '.hide'
  },

  waitUser : function() {
    let that = this;
    that.data.timeWaitFun = setInterval(function() {
      console.log('>>>>>wait...');
      let userAva = that.data.count % 2 == 0 ? '/images/defaultAva.png' : '/images/defaultAva2.png';
      let userText = that.data.count % 2 == 0 ? '等待中...' : '等待中.  .';
      that.data.count += 1;
      that.setData({ userAva: userAva});
      that.setData({ userText: userText });

      if (that.data.count >= 180) {
        wx.switchTab({
          url: '/pages/home/home'
        });
      }
    }, 1000);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _self = this;
    _self.setData({
      userInfo: app.globalData.userInfo
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    //发送创建房间
    this.createRoom();
    this.waitUser();
  },

  startPlay : function() {
    wx.request({
      url: cfg.host + cfg.mwurl.startPlay,
      data: {
        openId: wx.getStorageSync('loginUser').openId,
        roomTicket: wx.getStorageSync('roomTicket'),
        offset: wx.getStorageSync('paperOffset')
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.code != 1000) {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000
          })

          return;
        }

        let offset = wx.getStorageSync('paperOffset');
        wx.setStorageSync('paperOffset', offset + 1);
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST'
    })
  },

  createRoom : function() {
    let that = this;
    console.log('>>>' + app.globalData.loginUser);
    wx.request({
      url: cfg.host + cfg.mwurl.createRoom,
      data : {
        openId: wx.getStorageSync('loginUser').openId,
        nickName: app.globalData.userInfo.nickName,
        picUrl: app.globalData.userInfo.avatarUrl,
        roomTicket: wx.getStorageSync('roomTicket'),
        model: that.data.modelType
      },
      success : function(res) {
        console.log(res.data);
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
      method : 'POST'
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //注册回调函数
    app.globalData.socketCallBack = this.doSocket;
  },

  doSocket : function(res) {
    console.log('ready socket ' + res);
    let that = this;
    let wsDTO = res
    
    if (1002 === wsDTO.wsType) {
      //获取答卷数据
      
      wx.setStorageSync('paperInfo', wsDTO);
      wx.reLaunch({
        url: '/pages/paper/paper?fromType=10'
      })
    }

    if (1001 === wsDTO.wsType) {
      clearInterval(this.data.timeWaitFun);
      let userInfo = wsDTO.data;
      let userAva = userInfo.picUrl;
      let userText = userInfo.nickName;
      that.setData({ userAva: userAva, userText: userText, showStart : '.show'});
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('ready onUnload');
    this.leaveRoom2();
    clearInterval(this.data.timeWaitFun);
  },

  leaveRoom2 : function() {
    let that = this;
    wx.request({
      url: cfg.host + cfg.mwurl.leaveRoom,
      data: {
        openId: wx.getStorageSync('loginUser').openId,
        roomTicket: wx.getStorageSync('roomTicket')
      },
      success: function (res) {
        console.log(res.data);
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST'
    })
  },

  leaveRoom : function() {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定离开房间？',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: cfg.host + cfg.mwurl.leaveRoom,
            data: {
              openId: wx.getStorageSync('loginUser').openId,
              roomTicket: wx.getStorageSync('roomTicket')
            },
            success: function (res) {
              console.log(res.data);
              wx.reLaunch({
                url: '/pages/home/home',
                success: function () {
                  console.log('跳转到home页面');
                }
              });
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            method: 'POST'
          })
        } else if (res.cancel) {

        }
      }
    })


  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})